﻿package com.dLibs.rssViewer 
{
	import flash.net.URLRequest;
	import flash.net.URLLoader;
	import flash.events.*;

	public class RSSParser extends EventDispatcher 
	{		
		public static const rssEventComplete = "rssCarregado";
		public var url:String;
		public var rssXML:XML;
		public var rssOutput:String;
		public var rssTitle:String;
		private var myLoader:URLLoader;
		private var dataWritten:Event;
		
		public function RSSParser(rssURL:String) 
		{
			url = rssURL;
			var rssXMLURL:URLRequest = new URLRequest(url);
			myLoader = new URLLoader(rssXMLURL);
			myLoader.addEventListener("complete", xmlLoaded);
		}

		public function xmlLoaded(evtObj:Event):void 
		{ 
			rssXML = XML(myLoader.data);
			var outXML:XMLList = new XMLList();

			if (rssXML.namespace("") != undefined) 
			{
				default xml namespace = rssXML.namespace("");
			}
			for each (var item:XML in rssXML..item) 
			{
				var itemTitle:String = item.title.toString();
				var itemDescription:String = item.description.toString();
				var itemLink:String = item.link.toString();
				outXML += buildItemHTML(itemTitle, 
										itemDescription,
										itemLink);
			}
			XML.prettyPrinting = false;
			rssOutput = outXML.toXMLString();	
			rssTitle = rssXML.channel.title.toString();
			
			dataWritten = new Event(rssEventComplete, true);
			dispatchEvent(dataWritten);
		}

		private function buildItemHTML(itemTitle:String, itemDescription:String, itemLink:String):XMLList 
		{
			default xml namespace = new Namespace();
			var body:XMLList = new XMLList();
			body += new XML("<b>" + itemTitle + "</b>");
			var p:XML = new XML("<p>" + itemDescription + "</p>");
			
			var link:XML = <a></a>;
			link.@href = itemLink; // <link href="itemLinkString"></link>
			link.font.@color = "#008000"; // <font color="#008000"></font></a>
											// 0x008000 = green
			link.font = "More...";
			
			p.appendChild(<br/>); 
			p.appendChild(link); 
			body += p;
			return body;
		}	
	}
}